package com.example.address.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.address.service.AddressBookService;
import com.example.address_model.entity.AddressBook;
import com.example.common.Result;
import com.example.config.JwtConfig;
import com.example.user.service.UserService;
import com.example.user_model.entity.User;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 地址管理 前端控制器
 * </p>
 *
 * @author sjz
 * @since 2024-07-10
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Resource
    private AddressBookService addressBookService;

    @Resource
    private UserService userService;

    @Resource
    HttpServletRequest request;

    @Resource
    private JwtConfig jwtConfig;

    /**
     * 查询指定用户的全部地址
     */
    @GetMapping("/list")
    public Result<List<AddressBook>> list(AddressBook addressBook) {
        addressBook.setUserId(this.getId());
        log.info("addressBook:{}", addressBook);

        //条件构造器
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        wrapper.orderByDesc(AddressBook::getUpdateTime);

        //SQL:select * from address_book where user_id = ? order by update_time desc

        return Result.success(addressBookService.list(wrapper));
    }


    /**
     * 新增收货地址
     */
    @PostMapping
    public Result<AddressBook> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(this.getId());
        log.info("addressBook:{}", addressBook);
        addressBook.setCreateUser(this.getId());
        addressBook.setUpdateUser(this.getId());
        addressBookService.save(addressBook);
        return Result.success(addressBook);
    }


    /**
     * 设置默认地址
     */
    @Transactional
    @PutMapping("default")
    public Result<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, this.getId());
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);

        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return Result.success(addressBook);
    }


    /**
     * 根据id查询地址
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null) {
            return Result.success(addressBook);
        } else {
            return Result.error("没有找到该对象");
        }
    }


    /**
     * 修改收货地址信息
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody AddressBook addressBook) {
        log.info("addressBook:{}", addressBook);
        addressBookService.updateById(addressBook);
        return Result.success("修改成功");
    }

    /**
     * 根据id删除(批量删除)地址
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(@RequestParam List<String> ids) {
        log.info("ids:{}", ids);
        //删除地址表中的信息
        addressBookService.removeByIds(ids);
        return Result.success("删除成功");
    }


    /**
     * 结算页面,查询默认地址
     */
    @GetMapping("default")
    public Result<AddressBook> getDefault() {
        LambdaQueryWrapper<AddressBook> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AddressBook::getUserId, this.getId());
        wrapper.eq(AddressBook::getIsDefault, 1);

        //SQL:select * from address_book where user_id = ? and is_default = 1
        AddressBook addressBook = addressBookService.getOne(wrapper);

        if (null == addressBook) {
            return Result.error("没有找到该对象");
        } else {
            return Result.success(addressBook);
        }
    }


    /**
     * 利用请求头中的手机号,获取用户id,给其他方法调用
     *
     * @return
     */
    public String getId() {
        //获取请求头中的token
        String token = request.getHeader("Authorization").replace("\"", "");
        log.info("token:{}", token);
        Claims claims = JwtUtils.parseJwt(token, jwtConfig.getKey());
        //根据手机号查询当前用户
        String phone = claims.get("name", String.class);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user = userService.getOne(wrapper);
        //获取id
        return user.getId();
    }


}
